package net.socket;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;

public class ClientTester
{
	public static void main(String[] args)
	{
		int port = 8888;
		try
		{
			port = Integer.parseInt(args[0]);
		}
		catch (Exception e)
		{
		}
		try
		{
			ServerSocket server = new ServerSocket(port, 1);
			System.out.println("Listening for connections on port" + server.getLocalPort());
			while (true)
			{
				Socket connection = server.accept();
				try
				{
					System.out.println("Connection established with" + connection);
					Thread input = new InputThread(connection.getInputStream());
					input.start();
					Thread output = new InputThread(connection.getInputStream());
					output.start();
					try
					{
						input.join();
						output.join();
					}
					catch (Exception e)
					{
					}
				}
				catch (Exception e)
				{
				}
				finally
				{
					try
					{
						if (connection != null) connection.close();
					}
					catch (Exception e2)
					{
					}
				}
			}
		}
		catch (Exception e)
		{
		}
	}
}

class InputThread extends Thread
{
	InputStream	in;
	
	public InputThread(InputStream in)
	{
		this.in = in;
	}
	
	@Override
	public void run()
	{
		try
		{
			while (true)
			{
				int i = in.read();
				if (i == -1)
				{
					break;
				}
				System.out.write(i);
			}
		}
		catch (Exception e)
		{
		}
		try
		{
			in.close();
		}
		catch (Exception e)
		{
		}
	}
}

class OutputThread extends Thread
{
	private Writer	out;
	
	public OutputThread(OutputStream out)
	{
		this.out = new OutputStreamWriter(out);
	}
	
	@Override
	public void run()
	{
		String line;
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		try
		{
			while (true)
			{
				line = in.readLine();
				if (line.equals("."))
				{
					break;
				}
				out.write(line + "\r\n");
				out.flush();
			}
			out.close();
		}
		catch (Exception e)
		{
		}
	}
}
